package br.com.javamagazine.jdo;

import java.util.Collections;
import java.util.Date;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import br.com.javamagazine.UpdateServlet;

import com.google.appengine.api.datastore.Blob;

public class UserFotoDAO {

	private static final Logger log = Logger.getLogger(UpdateServlet.class
			.getName());

	private static Cache cache;

	public static UserFoto getUserFoto(String userName) {
		// Procura primeiro no cache
		UserFoto uf = (UserFoto) getCache().get(userName);

		if (uf != null) {
			log.info("Utilizando UserFoto do cache");
			return uf;
		}

		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			Query query = pm
					.newQuery("select from " + UserFoto.class.getName());
			query.setFilter("userId == paramUser");
			query.declareParameters("String paramUser");
			query.setUnique(true);
			uf = (UserFoto) query.execute(userName);

			getCache().put(userName, uf);
			return uf;
		} finally {
			if (pm != null)
				pm.close();
		}

	}

	public static void saveOrUpdateUserFoto(String userName, Blob imageData) {

		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			UserFoto uf = getUserFoto(userName);

			if (uf == null) {
				log.info(userName + " registrando foto.");
				uf = new UserFoto(userName, imageData);
				pm.makePersistent(uf);
			} else {
				log.info(userName + " atualizando os dados. ");
				uf.setUpdateTime(new Date());
				uf.setImageData(imageData);
				getCache().put(userName, uf);
			}
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	private static Cache getCache() {
		if (cache == null) {
			try {
				CacheFactory factory = CacheManager.getInstance()
						.getCacheFactory();
				cache = factory.createCache(Collections.emptyMap());
			} catch (CacheException cex) {
				log.severe("Problemas com o cache: " + cex.getMessage());
			}
		}
		return cache;
	}
}
